package com.jiezuo.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.jiezuo.auth.entity.Permission;
import com.jiezuo.auth.service.PermissionService;
import com.jiezuo.common.annotation.RepeatSubmit;
import com.jiezuo.common.base.BaseController;
import com.jiezuo.common.constant.SysConstant;
import com.jiezuo.common.enums.ResultEnums;
import com.jiezuo.common.util.*;
import com.jiezuo.common.vo.PageVo;
import com.jiezuo.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author 王帅
 * @Date 2020/7/29 10:49
 * @Version 1.0
 */
@Slf4j
@RequestMapping("/permission")
@RestController
@Transactional
//权限资源管理", tags = {"权限资源管理接口"})
public class PermissionController extends BaseController {

    @Autowired
    private PermissionService permissionService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    //权限资源列表", notes = "权限资源列表")
    @GetMapping("/findPage")
    public Result<IPage<Permission>> findPage(@ModelAttribute PageVo pageVo, @ModelAttribute Permission permission) {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        if (StringUtil.isNotEmpty(permission.getResource_name()))
            queryWrapper.like("resource_name", permission.getResource_name());
//        if (StringUtil.isNotEmpty(permission.getResource_method()))
//            queryWrapper.like("resource_method", permission.getResource_method());
        //查询根据某个字段排序
        queryWrapper.orderByAsc("sort");
        //查询未被删除的用户信息
        queryWrapper.ne("is_delete", "1");
        IPage<Permission> page = permissionService.page(PageUtil.initMpPage(pageVo), queryWrapper);
        return new ResultUtil<IPage<Permission>>().setData(page);
    }

    //查询不带分页列表", notes = "查询不带分页列表")
    @GetMapping("/findList")
    public Result<List<Permission>> findList(@ModelAttribute Permission permission) {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", "0");
        queryWrapper.orderByAsc("sort");
//        if (StringUtil.isNotEmpty(permission.getIs_data_authority()))
//            queryWrapper.like("is_data_authority", permission.getIs_data_authority());
        List<Permission> list = permissionService.list(queryWrapper);
        return new ResultUtil<List<Permission>>().setData(list);
    }

    @RepeatSubmit
    //添加", notes = "添加权限资源信息")
    @PostMapping("/save")
    public Result save(@RequestBody Permission permission) {
        VerifyUtil.notEmpty("上级权限", permission.getParent_id());
        VerifyUtil.notEmpty("类型", permission.getLink_type());
        boolean boo = permissionService.savePermission(permission);
        if (boo) {
            return new ResultUtil().setSuccessMsg(ResultEnums.OK.getReasonPhraseCN());
        } else {
            return new ResultUtil().setErrorMsg(ResultEnums.FAIL.getReasonPhraseCN());
        }
    }

    //修改", notes = "修改权限资源信息")
    @PostMapping("/update")
    public Result update(@RequestBody Permission permission) {
        VerifyUtil.notEmpty("数据序号", permission.getId());
        VerifyUtil.notEmpty("上级权限", permission.getParent_id());
        boolean boo = permissionService.updatePermission(permission);
        if (boo) {
            return new ResultUtil().setSuccessMsg(ResultEnums.OK.getReasonPhraseCN());
        } else {
            return new ResultUtil().setErrorMsg(ResultEnums.FAIL.getReasonPhraseCN());
        }
    }

    //删除", notes = "删除权限资源信息")
    @PostMapping("/delete/{id}")
    public Result delete(@PathVariable String id) {
        Permission permission = new Permission();
        permission.setId(id);
        permission.setIs_delete("1");
        boolean boo = permissionService.updateById(permission);
        //清除redis中的权限资源
        redisTemplate.delete(SysConstant.REDIS_ALL_PERMISSION);
        if (boo) {
            return new ResultUtil().setSuccessMsg(ResultEnums.OK.getReasonPhraseCN());
        } else {
            return new ResultUtil().setErrorMsg(ResultEnums.FAIL.getReasonPhraseCN());
        }
    }

    //批量删除", notes = "批量删除")
    //(name = "ids", value = "格式:[1,2,3]", dataType = "Array", required = true, paramType = "body")
    @PostMapping("/deleteBatch")
    public Result delete(@RequestBody String[] ids) {
        List<Permission> list = new ArrayList<>();
        for (String id : ids) {
            Permission permission = permissionService.getById(id);
            if (permission != null) {
                permission.setIs_delete("1");
                list.add(permission);
            }
        }
        if (list.size() > 0) {
            permissionService.updateBatchById(list);
        }
        //清除redis中的权限资源
        redisTemplate.delete(SysConstant.REDIS_ALL_PERMISSION);
        return new ResultUtil().setSuccessMsg(ResultEnums.OK.getReasonPhraseCN());
    }

    //菜单树", notes = "菜单树")
    @GetMapping("/menuTree")
    public Result<List<Permission>> menuTree(@ModelAttribute Permission permission) {
        long t1 = SystemClock.now();
        List<Permission> permissions = permissionService.menuTree(permission);
        long t2 = SystemClock.now();
        System.out.println("加载权限树耗时：" + (t2 - t1));
        return new ResultUtil().setData(permissions);
    }

    //获取子级", notes = "通过父ID获取权限资源子级")
    @GetMapping("getChildren")
    public Result<List<Permission>> getChildren(@RequestParam(required = false) String pid,
                                                @RequestParam(required = false) String resource_name,
                                                @RequestParam(value = "belongs", required = false, defaultValue = "0") String belongs) {
        List<Permission> permissions = permissionService.getChildren(pid, resource_name, belongs);
        return new ResultUtil<List<Permission>>().setData(permissions);
    }

    //是否开启数据权限", notes = "是否开启数据权限")
    @PostMapping("/isDataAuthority")
    public Result isDataAuthority(@RequestBody Permission permission) {
        VerifyUtil.notEmpty("数据序号", permission.getId());
//        VerifyUtil.notEmpty("is_data_authority", permission.getIs_data_authority());
        permissionService.updateById(permission);
        //清除redis中的权限资源
        redisTemplate.delete(SysConstant.REDIS_ALL_PERMISSION);
        return new ResultUtil().setSuccessMsg(ResultEnums.OK.getReasonPhraseCN());
    }

    //通过用户ID查询所有角色权限资源", notes = "通过用户ID查询所有角色权限资源（是按钮的且需要拦截的）")
    @GetMapping("/findRoleAndPermissionByUser")
    public Result<List<Map<String, Object>>> findRoleAndPermissionByUser(@RequestParam("user_id") String user_id,@RequestParam("user_name") String user_name) {
        VerifyUtil.notEmpty("用户ID", user_id);
        List<Map<String, Object>> result = permissionService.findRoleAndPermissionByUser( user_id, user_name);
        return new ResultUtil<List<Map<String, Object>>>().setData(result);
    }

    @GetMapping("/findButtonByUserId")
    public Result<List<String>> findButtonByUserId() {
        List<String> result = permissionService.findButtonByUserId(this.getLoginUser().getId());
        return new ResultUtil<List<String>>().setData(result);
    }

    @GetMapping("/findResourceDetails")
    public Result<List<Map<String,Object>>> findResourceDetails(String id) {
        List<Map<String,Object>> result = permissionService.findResourceDetails(id);
        return new ResultUtil<List<Map<String,Object>>>().setData(result);
    }

}
